import { getUserIdOrThrow } from '../../utils/guard'
import { writeFile, mkdir } from 'fs/promises'
import { join, dirname } from 'path'

export default eventHandler(async (event) => {
  getUserIdOrThrow(event)

  const files = await readMultipartFormData(event)
  if (!files || files.length === 0) {
    throw createError({ statusCode: 400, statusMessage: 'NO_FILE' })
  }

  const file = files[0]
  if (!file.filename || !file.data) {
    throw createError({ statusCode: 400, statusMessage: 'INVALID_FILE' })
  }

  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  if (!allowedTypes.includes(file.type || '')) {
    throw createError({ statusCode: 422, statusMessage: 'INVALID_FILE_TYPE' })
  }

  // 验证文件大小（5MB）
  if (file.data.length > 5 * 1024 * 1024) {
    throw createError({ statusCode: 422, statusMessage: 'FILE_TOO_LARGE' })
  }

  // 生成唯一文件名
  const ext = file.filename.split('.').pop() || 'jpg'
  const filename = `${Date.now()}-${Math.random().toString(36).substring(7)}.${ext}`
  const filepath = join(process.cwd(), 'public', 'uploads', filename)

  // 确保上传目录存在
  const uploadDir = dirname(filepath)
  await mkdir(uploadDir, { recursive: true })

  // 保存文件
  await writeFile(filepath, file.data)

  // 返回访问 URL（使用 API 路由）
  const url = `/api/uploads/${filename}`
  return { url }
})
